<?php
class ModelSalePurchaseOrder extends Model {
	public function getList($page = 1, $filter){
		$polist = M('po')
		->join('(select vendors.user_id,  vendor_name from vendors) v on v.user_id = po.vendor_id','left')
		->join('(select count(1) as count, po_id,packing_no from po_product group by po_id) ppc on ppc.po_id = po.id','left')
        ->join('(select logcenter_id, company as logcenter_company, address_1 as logcenter_address, logcenter_name from logcenters) lg on lg.logcenter_id = po.warehouse_id','left')
        //->join('(select user_id, company as logcenter_company, address_1 as logcenter_address, logcenter_name from logcenters) lg on lg.user_id = po.user_id','left')
		->order('po.date_added DESC')
		->where($filter)->page($page)->limit($this->config->get('config_limit_admin'))->select();
        return $polist;
	}
	public function getAllList($filter){
		$polist = M('po')
		->join('(select vendors.user_id,  vendor_name from vendors) v on v.user_id = po.vendor_id','left')
		->join('(select count(1) as count, po_id from po_product group by po_id) ppc on ppc.po_id = po.id','left')
        ->join('(select logcenter_id, company as logcenter_company, address_1 as logcenter_address, logcenter_name from logcenters) lg on lg.logcenter_id = po.warehouse_id','left')
        //->join('(select user_id, company as logcenter_company, address_1 as logcenter_address, logcenter_name from logcenters) lg on lg.user_id = po.user_id','left')
		->order('po.id DESC')
		->where($filter)->select();
		return $polist;
	}

	public function getPoOperationBySku($filter){
		$map['pp.sku'] = $filter['sku'];
		$map['_string'] = "po.deliver_time>='".$filter['filter_date_start']."' AND po.deliver_time<'".$filter['filter_date_end']."'";
		$map['po.status'] = array('gt',3);
		$map['lg.logcenter_id'] = $filter['filter_logcenter'];
		$po_operation = M('po_product')
		->alias('pp')
		->join('left join `po` ON po.id=pp.po_id')
        ->join('left join `logcenters` lg ON po.warehouse_id=lg.logcenter_id')
        //->join('left join `logcenters` lg ON po.user_id=lg.user_id')
		->where($map)
		->field('qty,name,unit_price,option_name,packing_no,deliver_time')
		->order('option_name,deliver_time')
		->select();
		return $po_operation;
	}

	public function getAllProductList($filter){
		$polist = M('po_product')
		->alias('pop')
		->join('LEFT JOIN `po` po ON po.id=pop.po_id')
		->join('(select vendors.user_id,  vendor_name from vendors) v on v.user_id = po.vendor_id','left')
		->join('(select count(1) as count, po_id from po_product group by po_id) ppc on ppc.po_id = po.id','left')
        ->join('(select logcenter_id, company as logcenter_company, address_1 as logcenter_address, logcenter_name from logcenters) lg on lg.logcenter_id = po.warehouse_id','left')
        //->join('(select user_id, company as logcenter_company, address_1 as logcenter_address, logcenter_name from logcenters) lg on lg.user_id = po.user_id','left')
		->order('po.id DESC')
		->group('pop.product_id,po.id')
		->where($filter)->select();
		// echo  M('po_product')->getLastsql();
		return $polist;
	}
	public function getListCount($filter){
		$count = M('po')
		->join('vendors v on v.user_id = po.vendor_id','left')
        ->join('left join `logcenters` lg ON po.warehouse_id=lg.logcenter_id')
		//->join(' `logcenters` lg on lg.user_id = po.user_id','left')
		->where($filter)
		->count();
		return $count;
	}
	public function getProducts($fitler){

		$res = M('product')
			->join('product_option_value pov on product.product_id = pov.product_id')
			->join('product_description pd on pd.product_id = product.product_id')
			->join('vendor on vendor.vproduct_id = product.product_id')
			->field('product.*, pd.*,vendor.product_cost,pov.product_code as vproduct_code ')
			->where($fitler)
			->where(array('pd.language_id'=>(int)$this->config->get('config_language_id')))
			->limit(5)->select();
			// echo M('product')->getLastsql();
		return $res;

	}
	public function getPo($id){
		$po = M('po')->find($id);
		if($po){
			$vendor = M('vendors')->where('user_id='.$po['vendor_id'])->find();
			$po['vendor'] = $vendor;
			$user = M('user')->find($po['user_id']);
			$po['creator'] = $user;
			//$logcenter_info = M('logcenters')->where(array('user_id'=>$po['user_id']))->find();
            $logcenter_info = M('logcenters')->where(array('logcenter_id'=>$user['logcenter_permission']))->find();//从创建采购单的用户信息中获取物流中心信息
			// $zone = M('zone')->where('zone_id='.$logcenter_info['zone_id'])->getField('name');
			$logcenter_info['shipping_zone_city'] = $zone.$logcenter_info['city'];
			$po['logcenter_info'] = $logcenter_info;
			if (!empty($po['warehouse_id'])) {
				$warehouse = M('warehouse')->where('warehouse_id='.$po['warehouse_id'])->find();
			}

			$po['warehouse'] = $warehouse;
		}
		return $po;
	}
	public function getPoProducts($id){
		$where['po_id'] = $id;
		$products = M('po_product')->where($where)->select();
		return $products;
	}
	public function getPoHistory($id){
		$where['po_id'] = $id;
		$history = M('po_history')->where($where)->select();
		return $history;
	}
	public function getVendors($filter_name=''){
		return M('vendors')->limit(5)->where(array('vendor_name'=>array('like', "%$filter_name%")))->select();
	}
	public function addPo($data, $user_id){
		$po_data['user_id'] = $user_id;
		$po_data['date_added'] = date('Y-m-d H:i:s', time());
		$po_data['status'] = $data['status'];
		$po_data['vendor_id'] = $data['vendor']['user_id'];
		// $po_data['deliver_time'] = $data['deliver_time'];
		$po_data['included_order_ids'] = $data['included_order_ids'];
		$po_data['warehouse_id'] = $data['warehouse_id'];
		$total = 0;
		foreach ($data['products'] as $key => $product) {
			$total += $product['qty']*$product['unit_price'];
		}
		$po_data['total'] = $total;

		if(!$data['id']){
			$po_id = M('po')->add($po_data);
			// var_dump($po_id);
			// echo M('po')->getLastsql();
		}
		foreach ($data['products'] as $key => $product) {
			$product_data['po_id'] = $po_id;
			$product_data['product_id'] = $product['product_id'];
			$product_data['qty'] = $product['qty'];
			$product_data['delivered_qty'] = $product['delivered_qty']?$product['delivered_qty']:0;
			$product_data['unit_price'] = $product['unit_price'];
			$product_data['price'] = $product_data['qty']* $product_data['unit_price'];
			$product_data['status'] = $product['status']?$product['status']:0;
			$product_data['name'] = $product['name'];
			$product_data['product_code'] = $product['product_code'];
			$product_data['sku'] = $product['sku'];
			$product_data['comment'] = $product['comment'];
			$product_data['sort_order'] = 0;
			$product_data['option_id'] = $product['option']['product_option_value_id'];
			$product_data['option_name'] = $product['option_list'];
			$product_data['packing_no'] = M('product')->where('product_id ='.$product['product_id'])->getField('packing_no');
			M('po_product')->add($product_data);
		}
		return $po_id;
	}

    public function updatePo($data, $user_id){
		if ($data['status']==0) {
			M('po')->where(array('id'=>$data['po_id']))->data(array('status'=>10))->save();

			M('po_product')->where(array('po_id'=>$data['po_id']))->delete();
			$price = 0;
			foreach ($data['products'] as $key => $product) {
				$product_data['po_id'] = $data['po_id'];
				$product_data['product_id'] = $product['product_id'];
				$product_data['qty'] = $product['qty'];
				$product_data['delivered_qty'] = $product['delivered_qty']?$product['delivered_qty']:0;
				$product_data['unit_price'] = $product['unit_price'];
				$product_data['price'] = $product_data['qty']* $product_data['unit_price'];
				$product_data['status'] = $product['status']?$product['status']:0;
				$product_data['name'] = $product['name'];
				$product_data['product_code'] = $product['product_code'];
				$product_data['sku'] = $product['sku'];
				$product_data['comment'] = $product['comment'];
				$product_data['sort_order'] = 0;
				$product_data['option_id'] = $product['option_id'];
				$product_data['option_name'] = $product['option_name'];
				$product_data['packing_no'] = $product['packing_no'];
				$price +=$product_data['qty']* $product_data['unit_price'];
				M('po_product')->add($product_data);
				$productNum = M('inventory')
				->field('qty_in_onway,product_code')
				->where(array('product_code' => $product['product_code'],'warehouse_id'=>$data['warehouse_id']))
				->find();
				if (empty($productNum)) {
					$datal = array(
						'warehouse_id'=>$data['warehouse_id'],
			  			'product_code'=>$product['product_code'],
			  		 	'qty_in_onway'=>$product['qty'],
						'date_added'=>date('Y-m-d H:i:s'));
				  	M('inventory')->data($datal)->add();
				}else{
					$total=(int)$productNum['qty_in_onway']+(int)$product['qty'];
					M('inventory')-> where(array('product_code' => $product['product_code'],'warehouse_id'=>$data['warehouse_id']))->data(array('qty_in_onway'=>$total,'date_modified'=>date('Y-m-d H:i:s')))->save();
				}
			}
			M('po')->data(array('total'=>$price,'date_modified'=>date('Y-m-d H:i:s')))->where(array('id'=>$data['po_id']))->save();
		}

		if ($data['status']==10) {
			$oldqty = M('po_product')->where(array('po_id'=>$data['po_id']))->field('product_code,qty')->select();
			foreach ($oldqty as $key => $value) {
				$productNumo = M('inventory')
				->field('qty_in_onway,product_code')
				->where(array('product_code' => $value['product_code'],'warehouse_id'=>$data['warehouse_id']))->find();
					$totalo=(int)$productNumo['qty_in_onway']-(int)$value['qty'];
				M('inventory')-> where(array('product_code' => $value['product_code'],'warehouse_id'=>$data['warehouse_id']))->data(array('qty_in_onway'=>$totalo,'date_modified'=>date('Y-m-d H:i:s')))->save();
			}
			$price = 0;
			M('po_product')->where(array('po_id'=>$data['po_id']))->delete();
			foreach ($data['products'] as $key => $product) {
				$product_data['po_id'] = $data['po_id'];
				$product_data['product_id'] = $product['product_id'];
				$product_data['qty'] = $product['qty'];
				$product_data['delivered_qty'] = $product['delivered_qty']?$product['delivered_qty']:0;
				$product_data['unit_price'] = $product['unit_price'];
				$product_data['price'] = $product_data['qty']* $product_data['unit_price'];
				$product_data['status'] = $product['status']?$product['status']:0;
				$product_data['name'] = $product['name'];
				$product_data['product_code'] = $product['product_code'];
				$product_data['sku'] = $product['sku'];
				$product_data['comment'] = $product['comment'];
				$product_data['sort_order'] = 0;
				$product_data['option_id'] = $product['option_id'];
				$product_data['option_name'] = $product['option_name'];
				$product_data['packing_no'] = $product['packing_no'];
				M('po_product')->add($product_data);
				$productNum = M('inventory')
				->field('qty_in_onway,product_code')
				->where(array('product_code' => $product['product_code'],'warehouse_id'=>$data['warehouse_id']))
				->find();
				$price +=$product_data['qty']* $product_data['unit_price'];
				if (empty($productNum)) {
					$datal = array(
						'warehouse_id'=>$data['warehouse_id'],
			  			'product_code'=>$product['product_code'],
			  		 	'qty_in_onway'=>$product['qty'],
						'date_added'=>date('Y-m-d H:i:s'));
				  	M('inventory')->data($datal)->add();
				}else{
					$total=(int)$productNum['qty_in_onway']+(int)$product['qty'];
					M('inventory')-> where(array('product_code' => $product['product_code'],'warehouse_id'=>$data['warehouse_id']))->data(array('qty_in_onway'=>$total,'date_modified'=>date('Y-m-d H:i:s')))->save();
				}
			}
			M('po')->data(array('total'=>$price,'date_modified'=>date('Y-m-d H:i:s')))->where(array('id'=>$data['po_id']))->save();
		}
		return $po_id;
	}

	public function deletePo($id) {
		$where['po_id'] = $id;
		$products = M('po_product');
		$products->where($where)->delete();
		$po = M('po');
		$po->where(array('id'=>$id))->delete();
	}

	public function setStock($po_id, $to_save_stock) {
		//添加入库历史记录
		$stock_history = M('po_product_stock_history');
		foreach ($to_save_stock as $po_product_id => $qty) {
			$stock_history->data(array('po_product_id'=>$po_product_id, 'qty'=>$qty, 'date_added'=>date('Y-m-d H:i:s')))->add();
		}
		//修改po单的delivered_qty
		$po_product = M('po_product');
		foreach ($to_save_stock as $po_product_id => $qty) {
			$delivered_qty = $po_product->where(array('id'=>$po_product_id, 'po_id'=>$po_id))->getField('delivered_qty');
			// var_dump($delivered_qty);die();
			$total = (int)$delivered_qty+(int)$qty;
			$po_product->where(array('id'=>$po_product_id, 'po_id'=>$po_id))->data(array('delivered_qty'=>$total))->save();
		}
	}

	public function changePoStatus($po_id, $po_status) {
		$po = M('po');
		$po->data(array('id'=>$po_id, 'status'=>$po_status))->save();
	}

	public function findOrderWithoutVendor($orders) {
		$order_query = M('order_product op')
		->join('left join vendor v on v.vproduct_id=op.product_id')
		->where('op.order_id in (' . implode(',', $orders) . ') AND v.vendor is null')
		->field('v.vendor as vendor_id, op.name as name')
		->select();
		return $order_query;
	}

	public function getUserIdByVendorId($vendor_id) {
		$query = M('vendors')
		->where('vendor_id='.$vendor_id)
		->field('user_id')
		->find();
		if($query) {
			return $query['user_id'];
		} else {
			return 0;
		}
	}

	public function getVendorIdsFromOrders($orders) {
		$order_query = M('order_product op')
		->join('vendor v on v.vproduct_id=op.product_id')
		->where('op.order_id in (' . implode(',', $orders) . ')')
		->field('v.vendor as vendor_id')
		->group('v.vendor')
		->select();
		return $order_query;
	}

	public function getPoDataFromOrders($orders, $vendor_id=0) {
		$order_query = M('order_product op')
		->join('left join order_option oo on oo.order_product_id=op.order_product_id')
		->join('vendor v on v.vproduct_id=op.product_id')
		->where('op.order_id in (' . implode(',', $orders) . ') AND v.vendor="' . $vendor_id . '"')
		->group('op.product_id, oo.product_option_value_id')
		->field('v.vendor as vendor_id, op.product_id as product_id, v.product_cost as unit_price,
			v.product_cost*op.quantity as price, op.name as name, oo.product_option_value_id as option_id, oo.value as option_name, "" as sku, "" as comment, SUM(op.quantity) as qty, op.order_id')
		->select();
		return $order_query;
	}

	public function setPoGeneratedFlag($orders) {
		foreach ($orders as $order_id) {
			$Order = M('order');
			$Order->where(array('order_id'=>$order_id))->setInc('po_generated');
		}
	}

	public function getToBillPo($cur_month, $end_month, $billed_po_ids, $vendor_id = 0) {
		$complete_status = array('4','6'); // 4=>'已收货', 6=>'审核完成'
		$map['date_added'] = array('between',array($end_month, $cur_month));
		$map['status'] = array('in', $complete_status);
		if(!empty($billed_po_ids)) {
			$map['id'] = array('not in', $billed_po_ids);
		}
		$map['vendor_id'] = array('eq', $vendor_id);
		$query = M('po')->where($map)->select();
		return $query;
	}

	public function getVendorIdsFromPo($cur_month, $end_month, $billed_po_ids) {
    $complete_status = array('4','6'); // 4=>'已收货', 6=>'审核完成'
		$map['date_added'] = array('between',array($end_month, $cur_month));
		$map['status'] = array('in', $complete_status);
		if(!empty($billed_po_ids)) {
			$map['id'] = array('not in', $billed_po_ids);
		}
		$query = M('po')->where($map)->group('vendor_id')->field('vendor_id')->select();
		return $query;
  }

  public function addPoHistory($po_id, $user_id, $operator_name, $comment,$comment2) {
  	$poHistory = M('po_history');
  	$data = array('po_id'=>$po_id, 'user_id'=>$user_id,
  		'operator_name'=>$operator_name, 'comment'=>$comment,
  		'notify'=>0, 'date_added'=>date('Y-m-d H:i:s'));
  	$poHistory->data($data)->add();
  	if ($comment2) {
  		$data = array('po_id'=>$po_id, 'user_id'=>$user_id,
  		'operator_name'=>$operator_name, 'comment'=>$comment2,
  		'notify'=>0, 'date_added'=>date('Y-m-d H:i:s'));
  		$poHistory->data($data)->add();
  	}

  }

  public function setPoTotal($id, $new_total) {
  	$po = M('po');
		$po->where(array('id'=>$id, 'status'=>3))->data(array('total'=>$new_total))->save();
  }

  public function addProductInitiai($data){
  	$id = $data['po_id'];
  	$to_save_stock = $data['to_save_stock'];
  	$po_product_model = M('po_product');
  	$map['po.id'] = $id;
  	$po_product_data = $po_product_model
  	->alias('pp')
  	->join('left join `po` ON po.id=pp.po_id')
    ->join('left join `logcenters` lg ON po.warehouse_id=lg.logcenter_id')
    //->join('left join `logcenters` lg ON lg.user_id=po.user_id')
  	->field('pp.id as po_product_id,pp.option_id,lg.logcenter_id,pp.product_id')
  	->where($map)
  	->select();

  	$product_initiai_model = M('product_initiai');
  	foreach ($po_product_data as $key => $value) {
  		if(isset($to_save_stock[$value['po_product_id']])){
  			$initiai_map['option_id'] = $value['option_id']?$value['option_id']:-1;
	  		$initiai_map['product_id'] = $value['product_id'];
	  		$initiai_map['logcenter_id'] = $value['logcenter_id'];
	  		$initiai_data = $product_initiai_model->where($initiai_map)->find();
	  		if($initiai_data){

	  			$edit_initiai_data['real_initiai'] = $to_save_stock[$value['po_product_id']] + $initiai_data['real_initiai'];
	  			$product_initiai_model->data($edit_initiai_data)->where($initiai_map)->save();
	  		}else{
	  			$edit_initiai_data['real_initiai'] = $to_save_stock[$value['po_product_id']];
	  			$edit_initiai_data['option_id'] = $value['option_id']?$value['option_id']:-1;
	  			$edit_initiai_data['product_id'] = $value['product_id'];
	  			$edit_initiai_data['logcenter_id'] = $value['logcenter_id'];
	  			$edit_initiai_data['date_added'] = date('Y-m-d h:i:s',time());
	  			$edit_initiai_data['initial_number'] = 0 ;
	  			$product_initiai_model->data($edit_initiai_data)->add();
	  		}
  		}
  	}
  }
  public function checkPoOrderDate($date_added,$order_status_id){

		$order_status_id_array = array(4,5,6,7,9);
		$date = strtotime(date('Y-m-d',time()));

		$date_added = strtotime($date_added);
		$day = ceil(($date-$date_added)/86400)+1;
		$color = '';
		if(!in_array($order_status_id, $order_status_id_array)){
			if($day<3){
				$color = 'black';
			}else{
				$color = 'red';
			}
		}
		return $color;

	}

	public function getPoIdsBySku($filter_sku){
		$map['p.sku'] = array('like','%'.$filter_sku.'%');
		$model = M('po_product');
		$pos = $model
		->alias('pp')
		->join('left join `product` p ON p.product_id=pp.product_id')
		->join('left join `po` ON pp.po_id = po.id')
		->where($map)
		->group('pp.po_id')
		->field('pp.po_id')
		->order('pp.po_id')
		->select();

		$save_data = array_column($pos, 'po_id');

		return $save_data;
	}

	public function getWarehouse(){
		$warehouse = M('warehouse')
			->alias('w')
			->field('w.warehouse_id,w.name')
			->where(array('w.status=1 and (w.type =1 or w.type=2)'))
			->select();
			return $warehouse;
	}

	public function addStock($id, $to_save_stock2){
		$model = M('po');
		$po = $model
		->alias('t')
		->where( "t.id =$id")
		->find();
		$i=0;
		foreach ($to_save_stock2 as $key => $value) {

			$po['product'][$i] = M('po_product')
			->alias('p')
			->field('p.unit_price,p.product_code')
			->where(array('p.po_id' => $id,'p.id'=>$key))
			->find();
			$po['product'][$i]['qty']=$value;
			$i++;
		}
		$time = time()-strtotime($po['date_added']);
		// var_dump($po);die();
	 	$stockin = M('stock_in');
	  	$data = array('refer_id'=>$po['id'],
	  		'refer_type_id'=>2,
	  		 'warehouse_id'=>$po['warehouse_id'],
	  		'user_id'=>$_SESSION['default']['user_id'],
	  		'buy_money'=>0,
	  		'status'=>1,
	  		'date_added'=>date('Y-m-d H:i:s'),
	  		'in_date'=>date('Y-m-d H:i:s'),
	  		'delivery_cycle'=>$time
	  		);
	  		$stockid = $stockin->data($data)->add();
	  		$total=0;
	  		$flag = false;
	  	foreach ($po['product'] as $key => $value) {
	  		if ($value['qty']>0) {
	  			$stockind = M('stock_in_detail');
			  	$datad = array('in_id'=>$stockid,
			  		'product_code'=>$value['product_code'],
			  		 'product_quantity'=>$value['qty'],
			  		 'product_price'=>$value['unit_price'],
			  		 'products_money'=>$value['unit_price']*$value['qty'],
					'date_added'=>date('Y-m-d H:i:s'),
	  				'delivery_cycle'=>$time);
			  	$total =$total+ $value['unit_price']*$value['qty'];
			  	$stockind->data($datad)->add();
	  			$flag = true;

	  		}
	  	}
	  	if ($flag) {
			$stockin->where(array('in_id'=>$stockid))->data(array('buy_money'=>$total))->save();

	  	}else{
	  		$stockin->where(array('in_id'=>$stockid))->delete();
	  		$stockid=0;
	  	}
		return 	$stockid;
	}


	public function addInventory($id,$to_save_stock2){
		$model = M('po');
		$warehouse_id = $model
		->alias('t')
		->where( "t.id =$id")
		->getField('warehouse_id');
		foreach ($to_save_stock2 as $key => $value) {
			$product_code = M('po_product')
			->where(array('po_id' => $id,'id'=>$key))
			->getField('product_code');
			$productNum = M('inventory')
			->field('available_quantity,product_code')
			->where(array('product_code' => $product_code,'warehouse_id'=>$warehouse_id))
			->find();
			if (empty($productNum)) {
				$data = array(
					'warehouse_id'=>$warehouse_id,
		  			'product_code'=>$product_code,
		  		 	'available_quantity'=>$value,
					'date_added'=>date('Y-m-d H:i:s'));
			  	M('inventory')->data($data)->add();
			}else{
				$total=(int)$productNum['available_quantity']+(int)$value;
				M('inventory')-> where(array('product_code' => $product_code,'warehouse_id'=>$warehouse_id))->data(array('available_quantity'=>$total,'date_modified'=>date('Y-m-d H:i:s')))->save();
			}
		}
	}
	public function getStockin($id){
		$stock_in =M('stock_in')
		->join('left join warehouse w on w.warehouse_id=stock_in.warehouse_id')
		->join('left join user v on v.user_id=stock_in.user_id')
		->join('left join inout_state i on i.id=stock_in.status')
		->field('stock_in.*, w.name as warehouse_name ,v.username,i.name as status_name')
		->where( "stock_in.refer_id =$id")
		->select();
		return $stock_in;
	}


	public function addStHistory($stockid, $user,$logcenter_name,$comments){
		$data = array(
					'in_id'=>$stockid,
		  			'user_id'=>$user,
		  			'operator_name'=>$logcenter_name,
		  		 	'comment'=>$comments,
					'date_added'=>date('Y-m-d H:i:s'));
		M('stock_in_history')->data($data)->add();
	}
	public function addmulti($user){
		$sql = "SELECT `warehouse_id`,`product_code`,(`safe_quantity`-`qty_in_onway`-`available_quantity`) AS quantity FROM `inventory` HAVING quantity>0";
		$query = $this->db->query($sql);

        $inventoryQty =  $query->rows;

        $sql = "SELECT `order_id`,`product_code`,`quantity` FROM `order_product` WHERE `order_id` IN (SELECT `order_id` FROM `order` WHERE `verify_status`=1)";
        $query = $this->db->query($sql);

        $orderQty =  $query->rows;
        foreach ($orderQty as $key => $value) {
			if (is_array($ret[$value['pCode']])) {
		        $ret[$value['product_code']]['quantity'] += $value['quantity'];
		        $ret[$value['product_code']]['order_ids'] .= ','.$value['order_id'];
		        $ret[$value['product_code']]['warehouse_id'] =10;
		        $ret[$value['product_code']]['product_code'] = $value['product_code'];
		    }else{
		        $ret[$value['product_code']]['quantity'] = $value['quantity'];
		        $ret[$value['product_code']]['order_ids'] = $value['order_id'];
		        $ret[$value['product_code']]['warehouse_id'] =10;
		        $ret[$value['product_code']]['product_code'] = $value['product_code'];
		    }
		}
		foreach ($inventoryQty as $key => $value) {
			if ($value['warehouse_id']==10) {
				if (array_key_exists($value['product_code'], $ret)) {
		        	$ret[$value['product_code']]['quantity'] += $value['quantity'];

				}
			}else{
				$retl[$value['product_code']]['quantity'] = $value['quantity'];
		        $retl[$value['product_code']]['order_ids'] .= ','.$value['order_id'];
		        $retl[$value['product_code']]['warehouse_id'] =$value['warehouse_id'];
			    $retl[$value['product_code']]['product_code'] = $value['product_code'];
			}

		}
		foreach ($ret as $key => $value) {
			$res = M('product')
			->join('product_option_value pov on product.product_id = pov.product_id')
			->join('option_value_description od on od.option_id = pov.option_id')
			->join('product_description pd on pd.product_id = product.product_id')
			->join('vendor on vendor.vproduct_id = product.product_id')
			->join('vendors on vendor.vendor = vendors.vendor_id')
			->field('pd.name, product.product_id,product.price,

			 product.sku, product.packing_no, pd.name,vendor.product_cost,vendors.user_id as vendor_id,pov.product_code as vproduct_code, pov.option_id, od.name as option_name')
			->where(array('pov.product_code'=>$key))->find();

			if (is_array($vendor[$res['vendor_id']])) {

		        $vendor[$res['vendor_id']]['vendor_id'] = $res['vendor_id'];
		     	$vendor[$res['vendor_id']]['order_ids'] .= ','.$value['order_id'];
		        $vendor[$res['vendor_id']]['total'] = $value['quantity']*$res['product_cost'];
		     	$prodata = array(
		        	'po_id' => $vendor[$res['vendor_id']]['po_id'],
		        	'product_id' => $res['vendor_id'],
		        	'qty' => $value['quantity'],
		        	'unit_price' => $res['product_cost'],
		        	'price' => $res['price'],
		        	'name' => $res['name'],
		        	'option_id' => $res['option_id'],
		        	'sku' => $res['sku'],
		        	'option_name' => $res['option_name'],
		        	'packing_no' => $res['packing_no'],
		        	'product_code' => $key,
		        	'date_added'=>date('Y-m-d H:i:s')

		        );
				M('po_product')->data($prodata)->add();

		    }else{
		        $vendor[$res['vendor_id']]['vendor_id'] = $res['vendor_id'];
		        $vendor[$res['vendor_id']]['total'] = $value['quantity']*$res['product_cost'];
		     	$vendor[$res['vendor_id']]['order_ids'] = $value['order_id'];
		        $podata = array(
		        	'user_id' => $user,
		        	'status' => 0 ,
		        	'vendor_id' =>$res['vendor_id'],
		        	'total' => 0,
		        	'included_order_ids' => '',
		        	'warehouse_id' => 10,
		        	'date_added'=>date('Y-m-d H:i:s')
		        );
		        // var_dump($podata);
			  	$po_id = M('po')->data($podata)->add();
			  	// echo M('po')->getLastsql();
			  	$vendor[$res['vendor_id']]['po_id'] = $po_id;
			  	$prodata = array(
		        	'product_id' => $res['vendor_id'],
		        	'qty' => $value['quantity'],
		        	'po_id' => $vendor[$res['vendor_id']]['po_id'],
		        	'unit_price' => $res['product_cost'],
		        	'price' => $res['price'],
		        	'name' => $res['name'],
		        	'option_id' => $res['option_id'],
		        	'sku' => $res['sku'],
		        	'option_name' => $res['option_name'],
		        	'packing_no' => $res['packing_no'],
		        	'product_code' => $key,
		        	'date_added'=>date('Y-m-d H:i:s')

		        );
				M('po_product')->data($prodata)->add();
				// var_dump($podata);
		     // var_dump($vendor);die();
				//M('po_product')->data($prodata)->add();

		    }
		}
		 var_dump($vendor);


	}

    /*
     * 获取可以修改的所有采购单信息
     * @author sonicsjh
     */
    public function getNewStatusPos() {
        $ret = array();
        $sql = "SELECT `id`,`warehouse_id`,`vendor_id`,`included_order_ids` FROM `po` WHERE `status`='0' ORDER BY `id` DESC";
        $query = $this->db->query($sql);
        foreach ($query->rows as $row) {
            $key = $row['warehouse_id'].'_'.$row['vendor_id'];
            $ret[$key]['PO_PK'] = $row['id'];
            $ret[$key]['includedOrderIds'] = $row['included_order_ids'];
            $sql = "SELECT `id`,`product_code`,`qty`,`packing_no`,`price` FROM `po_product` WHERE `po_id`='".$row['id']."'";
            $q = $this->db->query($sql);
            foreach ($q->rows as $r) {
                $ret[$key]['products'][$r['product_code']]['POP_PK'] = $r['id'];
                $ret[$key]['products'][$r['product_code']]['qty'] = $r['qty'];
                $ret[$key]['products'][$r['product_code']]['tPrice'] = $r['price'];
            }
        }
        return $ret;
    }

    /*
     * 根据 po_product 表PK，更新采购数量（一键采购）
     * @author sonicsjh
     */
    public function updateQtyByPoProductId($poProductId, $qty, $unitPrice, $packingNo) {
        $sql = "UPDATE `po_product` SET `qty`='".$qty."',`unit_price`='".$unitPrice."',`price`='".($qty*$unitPrice)."',`packing_no`='".$packingNo."' WHERE `id`='".$poProductId."'";
        $this->db->query($sql);
    }

    /*
     * 根据 po 表PK，更新采购总价（一键采购）
     * @author sonicsjh
     */
    public function updatePoByPK($poId, $data) {
        if (is_array($data) && count($data) > 0 && $poId > 0) {
            $t = array();
            foreach ($data as $k=>$v) {
                $t[] = "`".$k."`='".addslashes($v)."'";
            }
            $sql = "UPDATE `po` SET ".implode(',', $t)." WHERE `id`='".$poId."'";
            $this->db->query($sql);
        }
    }

    /*
     * 为已存在的采购单增加单品（一键采购）
     * @author sonicsjh
     */
    public function addPoProductInfo($poId, $poProduct) {
        $poProduct['po_id'] = $poId;
        M('po_product')->add($poProduct);
    }

    /*
     * 批量创建采购单（一键采购）
     * @author sonicsjh
     */
    public function addPos($poList) {
        $ret = array(
            'po'=>0,
            'pop'=>0,
        );
        foreach ($poList as $poInfo) {
            $poInfo['included_order_ids'] = $this->_initIncludedOrderIds($poInfo['included_order_ids']);
            $poProducts = $poInfo['products'];
            unset($poInfo['products']);
            $poId = M('po')->add($poInfo);
            if ($poId < 1) {
                continue;
            }
            $ret['po']++;
            foreach ($poProducts as $poProduct) {
                $poProduct['po_id'] = $poId;
                if (M('po_product')->add($poProduct)) {
                    $ret['pop']++;
                }
            }
        }
        return $ret;
    }

    /*
     *
     * @author sonicsjh
     */
    protected function _initIncludedOrderIds($includedOrderIds) {
        $ret = array();
        $temp = explode(',', $includedOrderIds);
        foreach ($temp as $orderId) {
            if (intval($orderId) > 0) {
                $ret[$orderId] = 1;
            }
        }
        return implode(',', array_keys($ret));
    }

     public  function getPoStatusById($po_id) {
     	$sql = "select status,warehouse_id,id from po where id =".(int)$po_id;
     	$query = $this->db->query($sql);
     	$data = $query->row;
     	return $data;
    }


    public function addInQty($podata){
    	$product = M('po_product')->where(array('po_id'=>$podata['id']))->select();
		foreach ($product as $key => $product) {
			$productNum = M('inventory')
			->field('qty_in_onway,product_code')
			->where(array('product_code' => $product['product_code'],'warehouse_id'=>$podata['warehouse_id']))
			->find();
			if (empty($productNum)) {
					$datal = array(
						'warehouse_id'=>$podata['warehouse_id'],
			  			'product_code'=>$product['product_code'],
			  		 	'qty_in_onway'=>$product['qty'],
						'date_added'=>date('Y-m-d H:i:s'));
				  	M('inventory')->data($datal)->add();
				}else{
					$total=(int)$productNum['qty_in_onway']+(int)$product['qty'];
					M('inventory')-> where(array('product_code' => $product['product_code'],'warehouse_id'=>$podata['warehouse_id']))->data(array('qty_in_onway'=>$total,'date_modified'=>date('Y-m-d H:i:s')))->save();
			}
		}
		M('po')->where(array('id'=>$podata['id']))->data(array('status'=>10))->save();

    }

}
